package com.sqxgg.drugstore.security.controler;

import com.sqxgg.drugstore.security.entity.ImageCode;
import com.sqxgg.drugstore.security.interfaceClass.ValidateCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Fant.J.
 */
@RestController
public class ValidateCodeController {

    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    /**
     * 引入 session
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;

    @GetMapping("/code/image")
    public Map<String, String>  createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = imageCodeGenerator.createCode(new ServletWebRequest(request));
        //将随机数 放到Session中
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
        // 验证码转base64
        String base64Code = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(imageCode.getImage(), "PNG", bos);
        byte[] bytes = bos.toByteArray();
        Base64.Encoder encoder = Base64.getEncoder();
        base64Code = encoder.encodeToString(bytes);
        Map<String, String> result = new HashMap<>();
        result.put("data","data:image/png;base64," + base64Code);
        result.put("key","521213344");
        return result;
        //写给response 响应
        //ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
    }
}
